package main.java.indi.zyj.sword;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Partition {

    List<List<String>> res = null;

    Deque<String> path = null;

    public List<List<String>> partition(String s) {

        if (s == null || s.length() == 0) {
            return res;
        }

        res = new ArrayList<>();
        path = new LinkedList<>();
        backtrack(s, 0);

        return res;
    }

    private void backtrack(String s, int startIndex) {

        if (startIndex == s.length()) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIndex; i < s.length(); i++) {
            if (isPalindrome(s, startIndex, i)) {
                path.add(s.substring(startIndex, i + 1));
                backtrack(s, i + 1);
                path.removeLast();
            }
        }

    }

    private boolean isPalindrome(String s, int left, int right) {
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }


}
